package com.demo.sso.controller.sso;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.demo.sso.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录页面 - GET请求,进入登录界面
     */
    @GetMapping("/login")
    public String loginPage() {
        return "redirect:/login.html";
    }

    /**
     * 用户登录接口 - POST请求
     */
    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, String redirect, HttpServletResponse response) throws IOException {
        // 验证用户名密码是否正确
        boolean loginSuccess = userService.login(username, password);
        if (!loginSuccess) {
            return SaResult.error("登录失败，账号或密码错误");
        }

        try {
            // 登录成功，生成token
            StpUtil.login(username);
            
            // 检查token是否生成成功
            String token = StpUtil.getTokenValue();
            // 登录成功后可返回
            if (token == null || token.isEmpty()) {
                return SaResult.error("token生成失败，请检查Redis服务是否正常运行");
            }

            // 如果有重定向参数，则重定向
            if (redirect != null && !redirect.isEmpty()) {
                response.sendRedirect(redirect);
                return null;
            }

            // 返回登录信息
            return SaResult.ok("登录成功")
                    .set("token", token)
                    .set("username", username)
                    .set("expireTime", StpUtil.getTokenTimeout());
        } catch (Exception e) {
            e.printStackTrace();
            return SaResult.error("登录过程中发生错误: " + e.getMessage());
        }
    }

    /**
     * 用户退出接口
     */
    @PostMapping("/logout")
    @ResponseBody
    public SaResult logout() {
        try {
            StpUtil.logout();
            return SaResult.ok("退出成功");
        } catch (Exception e) {
            return SaResult.error("退出失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户信息
     */
    @RequestMapping("/getCurrentUser")
    @ResponseBody
    public SaResult getCurrentUser() {
        try {
            // 检查是否登录
            if (!StpUtil.isLogin()) {
                return SaResult.error("未登录");
            }
            
            String username = StpUtil.getLoginIdAsString();
            if (username == null) {
                return SaResult.error("未登录");
            }
            Object userInfo = userService.getUserByUsername(username);
            return SaResult.ok().set("userInfo", userInfo);
        } catch (cn.dev33.satoken.exception.NotLoginException e) {
            return SaResult.error("您尚未登录，请先登录");
        } catch (Exception e) {
            return SaResult.error("获取用户信息失败: " + e.getMessage());
        }
    }
}